package com.topofstack.flp;

import com.topofstack.flp.ui.HomeActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity implements OnClickListener {
    EditText pass0;
    EditText pass;
    Button btnEnter;
	
	FLPApplication application;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_login);
        
        pass0 = (EditText) findViewById(R.id.txt_pass0);
        pass = (EditText) findViewById(R.id.txt_pass);
        btnEnter = (Button) findViewById(R.id.btn_enter);
        btnEnter.setOnClickListener(this);
        
        application = (FLPApplication)getApplication();
        
        String savedPass = application.getPreferenceManager().getPass();
        if(savedPass == null){
        	pass0.setVisibility(EditText.VISIBLE);
        	pass0.setHint("Enter new passscode");
        	pass.setHint("Re-enter new passcode");
        }
        else{
        	
        }
        
        pass0.setText("");
        pass.setText("");
    }



	@Override
	public void onClick(View sender) {
		if(sender == btnEnter){
			String savedPass = application.getPreferenceManager().getPass();
			String thePass = pass.getText().toString();
			String thePass0 = pass0.getText().toString();
			
			pass0.setText("");
	        pass.setText("");
			
			if(savedPass == null){
				if(thePass != null && thePass0 != null && thePass.length() > 0 && thePass0.length() > 0 && thePass.equals(thePass0)){
					application.getPreferenceManager().setPass(thePass);
					enterVault();
				}
				else{
					FLPApplication.showAlert(this,
							"Passcode cannot be empty and you must enter same passcode in both text fields to confirm.", 
							"Oops!");
				}
			}
			else{
				String login_resp = application.getPreferenceManager().login(thePass);
				if(login_resp == null){
					enterVault();
				}
				else{
					String alertTitle;
					if(login_resp.contains("seconds time")){
						alertTitle = "Wait!";
					}
					else{
						alertTitle = "Invalid login";
					}
					FLPApplication.showAlert(this,
							"", 
							alertTitle);
				}
			}
		}
	}
	
	void enterVault(){
		Intent i = new Intent(this, HomeActivity.class);
		startActivity(i);
	}
	
}